package cscie160.project;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.EnumSet;
import java.util.TreeMap;

public class SecurityImplementation extends UnicastRemoteObject implements Security
{
    private transient TreeMap<Integer, AccountSecurityInfo> accountSecurityInfoList;

    public SecurityImplementation() throws RemoteException
    {
        accountSecurityInfoList = new TreeMap<Integer, AccountSecurityInfo>();

        addNewAccount(0000001, 1234, EnumSet.of(Commands.DEPOSIT, Commands.WITHDRAW, Commands.BALANCE));
        addNewAccount(0000002, 2345, EnumSet.of(Commands.DEPOSIT, Commands.BALANCE));
        addNewAccount(0000003, 3456, EnumSet.of(Commands.WITHDRAW, Commands.BALANCE));
    }

    private boolean addNewAccount(int accountNumber, int PIN, EnumSet<Commands> authorizedCommands)
    {
        // Check if account already exists
        if (findAccountInfo(accountNumber) != null)
            return false;
        AccountSecurityInfo newInfo = new AccountSecurityInfo(accountNumber, PIN, authorizedCommands);
        accountSecurityInfoList.put(Integer.valueOf(accountNumber), newInfo);
        return true;
    }

    private AccountSecurityInfo findAccountInfo(int accountNumber)
    {
        return accountSecurityInfoList.get(Integer.valueOf(accountNumber));
    }

    public boolean authenticate(AccountInfo info) throws RemoteException
    {
        AccountSecurityInfo storedInfo = findAccountInfo(info.getAccountNumber());
        if (storedInfo == null)
            return false;
        return info.getPIN() == storedInfo.getPIN();
    }

    public boolean authorize(int accountNumber, Commands command) throws RemoteException
    {
        AccountSecurityInfo storedInfo = findAccountInfo(accountNumber);
        if (storedInfo == null)
            return false;
        return storedInfo.hasAuthorization(command);
    }
}
